package com.credit.core.config;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
 
/**    
 *     
 * 项目名称：core    
 * 类名称：ZooKeeperFactory    
 * 类描述：    zk初始化工厂
 * 创建人：huan   
 * 创建时间：2016年3月21日 下午2:56:49    
 * 修改人：huan    
 * 修改时间：2016年3月21日 下午2:56:49    
 * 修改备注：    
 * @version     
 *     
 */
public class ZooKeeperFactory {
 
    public static final String CONNECT_STRING = "zookeeper.address";
     
    public static final String MAX_RETRIES = "zookeeper.max_retries";
 
    public static final String BASE_SLEEP_TIMEMS = "zookeeper.base_sleep_timems";
 
    public static final String NAME_SPACE = "zookeeper.name_space";
    
    public static final String FILENAME = "config.properties";
    
    public static final String ENCODING = "UTF-8";
 
    public static CuratorFramework get() {
    	InputStream inputStream = null;
    	Properties properties = null;
		try {
			inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(FILENAME);		// properties.load(Prop.class.getResourceAsStream(fileName));
			if (inputStream == null)
				throw new IllegalArgumentException("Properties file not found in classpath: " + FILENAME);
			properties = new Properties();
			properties.load(new InputStreamReader(inputStream, ENCODING));
		} catch (IOException e) {
			throw new RuntimeException("Error loading properties file.", e);
		}
		finally {
			if (inputStream != null) try {inputStream.close();} catch (IOException e) {e.printStackTrace();}
		}
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(Integer.parseInt(properties.getProperty(BASE_SLEEP_TIMEMS)) ,Integer.parseInt(properties.getProperty(MAX_RETRIES)) );
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(properties.getProperty(CONNECT_STRING))
                .retryPolicy(retryPolicy)
                .namespace(properties.getProperty(NAME_SPACE))
                .build();
        client.start();
        return client;
    }
}
